
package finalproject.server;


import java.util.List;

import javax.jdo.PersistenceManager;

import finalproject.server.PmfSingleton;
import finalproject.shared.Student;
import finalproject.shared.Persoon;


public class StudentDAOPmf implements StudentDAO {

	
	public void addStudent(Student student) {
		PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
		try {
			
			Persoon persoon = student.getPersoon();
			pm.makePersistent(student);
		} finally {
			pm.close();
		}
	}

	
	@SuppressWarnings("unchecked")
	public List<Student> listStudenten() {
		PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
		String query = "select from " + Student.class.getName();
		return (List<Student>) pm.newQuery(query).execute();
	}

	
	public void removeStudent(Student student) {
		PersistenceManager pm =PmfSingleton.get().getPersistenceManager();
		try {
			pm.currentTransaction().begin();

			student = pm.getObjectById(Student.class, student.getStudentNr());
			pm.deletePersistent(student);

			pm.currentTransaction().commit();
		} catch (Exception ex) {
			pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
		} finally {
			pm.close();
		}
	}

	
	public void updateStudent(Student student) {
		PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
		
		Persoon persoon = student.getPersoon();
		
		String naam = persoon.getNaam();
		
		String email = student.getEmail();
		String richting = student.getRichting();
		String klas = student.getKlas();


		try {
			pm.currentTransaction().begin();
			
			student = pm.getObjectById(Student.class, student.getStudentNr());
			persoon = student.getPersoon();
			persoon.setNaam(naam);
			student.setEmail(email);
			student.setPersoon(persoon);
			student.setRichting(richting);
			student.setKlas(klas);

			pm.makePersistent(student);
			pm.currentTransaction().commit();
		} catch (Exception ex) {
			pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
		} finally {
			pm.close();
		}
	}

}
